package cn.cnf.service.impl;

import cn.cnf.common.enums.WorkType;
import cn.cnf.common.exception.CustomException;
import cn.cnf.common.utils.UserRequestUtil;
import cn.cnf.entity.Comic;
import cn.cnf.entity.Novel;
import cn.cnf.entity.Subscribe;
import cn.cnf.entity.User;
import cn.cnf.entity.vo.SubscribeInfo;
import cn.cnf.mapper.SubscribeMapper;
import cn.cnf.service.ChapterService;
import cn.cnf.service.ComicService;
import cn.cnf.service.MoneyRecordService;
import cn.cnf.service.NovelService;
import cn.cnf.service.SubscribeService;
import cn.cnf.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 服务接口实现
 *
 * @author ZhuMeiYi
 * @description
 * @since 2020-12-25 12:19:41
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class SubscribeServiceImpl extends ServiceImpl<SubscribeMapper, Subscribe> implements SubscribeService {
    private final SubscribeMapper subscribeMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ComicService comicService;
    @Autowired
    private NovelService novelService;
    @Autowired
    private MoneyRecordService moneyRecordService;

    /**
     * 确认订阅
     *
     * @param subscribe
     * @return
     */
    @Override
    public String confirmSubscribe(Subscribe subscribe) {
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        if (ifSubscribe(user.getUsername(), subscribe.getSubscribeId(), subscribe.getChapterId())) {
            throw new CustomException("请勿重复订阅");
        }
        subscribe.setUserId(user.getId());
        // 获取订阅需要的钱
        BigDecimal needMoney = chapterService.getById(subscribe.getChapterId()).getNeedMoney();
        // 用户打赏作品
        moneyRecordService.rewardsWork(user.getUsername(), subscribe.getSubscribeId(), WorkType.getByValue(subscribe.getType()), needMoney);
        if (subscribe.getType().equals(WorkType.COMIC.getValue())) {
            // 订阅数+1
            comicService.updateSubscribe(subscribe.getSubscribeId(), 1);
        } else if (subscribe.getType().equals(WorkType.NOVEL.getValue())) {
            novelService.updateSubscribe(subscribe.getSubscribeId(), 1);
        }
        if (save(subscribe)) {
            return subscribe.getSubscribeId();
        } else {
            throw new CustomException("订阅失败");
        }
    }

    /**
     * 取消订阅
     *
     * @param subscribe
     * @return
     */
    @Override
    public String cancelSubscribe(Subscribe subscribe) {
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        boolean remove = remove(new LambdaQueryWrapper<Subscribe>()
                .eq(Subscribe::getUserId, user.getId())
                .eq(Subscribe::getSubscribeId, subscribe.getSubscribeId())
                .eq(Subscribe::getType, subscribe.getType()));
        if (remove) {
            if (WorkType.COMIC.equals(WorkType.getByValue(subscribe.getType()))){
                comicService.updateSubscribe(subscribe.getSubscribeId(), -1);
            }else if (WorkType.NOVEL.equals(WorkType.getByValue(subscribe.getType()))){
                novelService.updateSubscribe(subscribe.getSubscribeId(),-1);
            }else {
                throw new CustomException("未知的作品类型");
            }
            return subscribe.getSubscribeId();
        } else {
            throw new CustomException("取消订阅失败");
        }
    }

    @Override
    public List<SubscribeInfo> getAllComic() {
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        return subscribeMapper.getAllSubscribeComic(user.getId());

    }

    @Override
    public List<SubscribeInfo> getAllNovel() {
        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        return subscribeMapper.getAllSubscribeNovel(user.getId());
    }

    @Override
    public boolean ifSubscribe(String username, String subscribeId, String chapterId) {
        User user = userService.findUserByUsername(username);
        List<Subscribe> list = list(new LambdaQueryWrapper<Subscribe>()
                .select(Subscribe::getSubscribeId)
                .eq(Subscribe::getUserId, user.getId())
                .eq(Subscribe::getChapterId, chapterId)
                .eq(Subscribe::getSubscribeId, subscribeId));
        return !CollectionUtils.isEmpty(list);
    }

    @Override
    public boolean authority(String username, String workId, String chapterId, WorkType workType) {

        if (StringUtils.isBlank(workId)) {
            throw new CustomException("没有传入作品id");
        } else if (StringUtils.isBlank(chapterId)) {
            throw new CustomException("没有传入章节id");
        }

        User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
        // 判断是否是作者
        if (WorkType.COMIC.equals(workType)) {
            List<Comic> list = comicService.list(new LambdaQueryWrapper<Comic>()
                                           .eq(Comic::getId, workId)
                                           .eq(Comic::getAuthorId, user.getId()));
            if (!CollectionUtils.isEmpty(list)) {
                return true;
            }
        } else if (WorkType.NOVEL.equals(workType)) {
            List<Novel> list = novelService.list(new LambdaQueryWrapper<Novel>().eq(Novel::getId, workId).eq(Novel::getAuthorId, user.getId()));
            if (!CollectionUtils.isEmpty(list)) {
                return true;
            }
        }
        /*
        1、判断漫画还是小说
        2、判断是否有关联
        */
        if(WorkType.COMIC.equals(workType)){
            List<Novel> list = novelService.list(new LambdaQueryWrapper<Novel>()
                    .eq(Novel::getSign,workId)
                    .eq(Novel::getAuthorId, user.getId()));
//            for(Comic comic : list){
//                LambdaQueryWrapper<Novel> wrapper = Wrappers.lambdaQuery();
//                wrapper.eq(Novel::getSign,comic.getSign());
//                List<Novel> list1 = novelService.list(wrapper);
//                if(list1.size()>0){
//                    return true;
//                }
//            }
            if(list.size()>0){
                   return true;
                }

        }else if(WorkType.NOVEL.equals(workType)){
            List<Comic> list = comicService.list(new LambdaQueryWrapper<Comic>()
                                           .eq(Comic::getSign,workId)
                                           .eq(Comic::getAuthorId,user.getId()));
//            for(Comic comic : list){
//                LambdaQueryWrapper<Comic> wrapper = Wrappers.lambdaQuery();
//                wrapper.eq(Comic::getSign,novel.getSign());
//                List<Comic> list1 = comicService.list(wrapper);
//                if(list1.size()>0){
//                    return true;
//                }
//            }
            if(list.size()>0){
                    return true;
               }

        }
        // 如果不是作者，查看是否订阅
        return ifSubscribe(username, workId, chapterId);
    }


}